package com.bmc.arsys.demo.javadriver;

import java.util.Random;

/**
 * @author Yucheng Huang
 * May 24, 2007
 */
class RandomNumberThread extends Thread {
    Object waitObj;
    boolean numberAvailable = false;
    int value;
    Random rd;

    public RandomNumberThread(int randomNumberSeed) {
        waitObj = new Object();
        rd = new Random((long) randomNumberSeed);
    }

    public void setWaitObjToNull() {
        waitObj = null;
    }

    public void run() {
        try {
            while (true) {
                synchronized (waitObj) {
                    while (numberAvailable == true) {
                        try {
                            waitObj.wait();
                        } catch (InterruptedException e) {
                        }
                    }
                    value = rd.nextInt(JavaDriver.RAND_MAX);
                    numberAvailable = true;
                    waitObj.notifyAll();
                }
            }
        } catch (Exception e) {
            // System.out.println( "Interrupted Exception ...in simplethread run");
        }

    }

    public int getRandomNumber() {
        int val = 0;

        synchronized (waitObj) {
            while (numberAvailable == false) {
                try {
                    waitObj.wait();
                } catch (InterruptedException e) {
                }
            }
            numberAvailable = false;
            waitObj.notifyAll();
            val = value;
        }
        return val;
    }
}
